package com.dky.satell.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.dky.satell.entity.OfflineFileMeta;
import com.dky.satell.util.MD5Utils;
import com.dky.satell.service.OfflineFileMetaService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.File;

/**
 * @ClassName AccessController
 * @Description
 * @Author superz
 * @Date 2021/4/28 10:41
 * @Version 1.0
 **/
@Slf4j
@RestController
@RequestMapping("/gather/access")
public class AccessController {

    /**
     * 下载本地路径
     */
    @Value("${file.downloadPath}")
    private String downloadPath;

    @Autowired
    private OfflineFileMetaService offlineFileMetaService;

    @GetMapping(value = "/download/{proxyFileName}")
    @ApiOperation(value="下载对应的离线数据文件")
    public void downloadBIOFile(@PathVariable("proxyFileName") String proxyFileName, HttpServletResponse response){
        log.info("/access/download/" + proxyFileName);
        OfflineFileMeta offlineFileMeta = offlineFileMetaService.selectOfflineMetaFileByName(proxyFileName);
        if(offlineFileMeta == null) {
            log.error("文件不存在");
            response.setStatus(HttpStatus.NOT_FOUND.value());
            return;
        }
        File file = new File(downloadPath + proxyFileName);
        if (!file.exists() || !file.isFile()) {
            log.error("文件不存在");
            response.setStatus(HttpStatus.NOT_FOUND.value());
            return;
        }
        String preSign = offlineFileMeta.getSign();
        String sign = MD5Utils.getFileMD5String(file);
        if(!preSign.equals(sign)) {
            log.error("文件[{}]已被篡改，无法下载", proxyFileName);
            response.setStatus(HttpStatus.NOT_FOUND.value());
            return;
        }
        response.setContentType("application/octet-stream;charset=UTF-8"); // application/mspowerpoint  application/msword
        response.addHeader("Content-Disposition", "attachment;fileName=" + StrUtil.str(StrUtil.bytes(proxyFileName, "utf-8"), "ISO_8859_1"));
        try {
            FileUtil.writeToStream(file, response.getOutputStream());
        } catch (Exception e) {
            log.error("文件下载失败", e);
        }
    }


}
